﻿using Collections.Pooled;
using FieldTools.Client.Command;
using FieldTools.Client.Model.Window;
using FieldTools.Client.View;
using FieldTools.Client.View.Window;
using FieldTools.Util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// 
    /// </summary>
    public class PicsShowViewModel : NotificationObject, IDisposable, ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public PicsShowViewModel()
        {
            Init();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sources"></param>
        public PicsShowViewModel(PooledList<Pic> sources)
        {
            Init();
            if (sources != null && sources.Count != 0)
            {
                Pics = sources;
                Pic = sources.FirstOrDefault();
                //ShowNow = OriginalStatus ? Pic?.BitmapFrameE?.BitmapImageSource : Pic?.BitmapFrameE?.Thumbnail;
                if (Pic != null && Pic.BitmapFrameE != null)
                {
                    //Pic.BitmapFrameE.BitmapImageSource.DownloadProgress += BitmapFrameE_DownloadProgress;
                }
            }
        }

        /// <summary>
        /// 初始化一些基础数据
        /// </summary>
        public void Init()
        {
            Pic ??= new Pic()
            {
                Title = "logo",
                From = "this soft",
                Subject = "",
                BitmapFrameE = new BitmapFrameEX(System.IO.Path.GetFullPath("./logo.png"))
            };
        }
        #region 实体
        PicShowModel obj = new();
        /// <summary>
        /// 图片资源
        /// </summary>
        public PooledList<Pic>? Pics
        {
            get { return obj.Pics;  }
            set { obj.Pics = value; this.RaisePropertyChanged(nameof(Pics)); }
        }

        /// <summary>
        /// 是否预加载
        /// </summary>
        public bool PreLoadStatus
        {
            get { return obj.PreLoadStatus; }
            set { obj.PreLoadStatus = value; this.RaisePropertyChanged(nameof(PreLoadStatus)); }
        }

        //private Pic? pic = new() { Title = "测试图片", Index = 0, BitmapFrameE = new() { BaseUri = new Uri("https://upload-bbs.mihoyo.com/upload/2022/05/30/22630933/5c953b099b56d0a0eae8b0bb4ad0709b_4907153359308521727.jpg") } };
        private Pic? pic;
        /// <summary>
        /// 当前展示图片源
        /// </summary>
        public Pic? Pic
        {
            get { return pic; }
            set { pic = value; this.RaisePropertyChanged(nameof(Pic)); }
        }

        private ImageSource showNow;
        /// <summary>
        /// 当前图片
        /// </summary>
        public ImageSource ShowNow
        {
            get { return showNow; }
            set { showNow = value; this.RaisePropertyChanged(nameof(ShowNow)); }
        }


        private bool? isActive = false;
        /// <summary>
        /// 是否加载中
        /// </summary>
        public bool? IsActive
        {
            get { return isActive; }
            set { isActive = value; this.RaisePropertyChanged(nameof(IsActive)); }
        }

        /// <summary>
        /// 是否加载原图
        /// </summary>
        public bool OriginalStatus
        {
            get { return obj.OriginalStatus; }
            set { obj.OriginalStatus = value; this.RaisePropertyChanged(nameof(OriginalStatus)); }
        }

        private bool isOpenDrawer = false;
        /// <summary>
        /// 是否打开列表抽屉
        /// </summary>
        public bool IsOpenDrawer
        {
            get { return isOpenDrawer; }
            set { isOpenDrawer = value; this.RaisePropertyChanged(nameof(IsOpenDrawer)); }
        }


        #endregion

        #region 事件
        private BaseCommand? keyEvent;
        /// <summary>
        /// 按键事件
        /// </summary>
        public BaseCommand KeyEvent
        {
            get
            {
                if (keyEvent == null)
                {
                    keyEvent = new BaseCommand(new Action<object>(o =>
                    {
                        
                    }),
                    new Func<object, bool>(o =>
                    {
                        var e = (KeyEventArgs)o;
                        if(e.KeyStates == Keyboard.GetKeyStates(Key.Left))
                        {
                            Pre();
                        }
                        else if(e.KeyStates == Keyboard.GetKeyStates(Key.Right))
                        {
                            Next();
                        }
                        return true;
                    }));
                }
                return keyEvent;
            }
        }

        private BaseCommand? nextPic;
        /// <summary>
        /// 下一张
        /// </summary>
        public BaseCommand NextPic
        {
            get
            {
                if (nextPic == null)
                {
                    nextPic = new BaseCommand(new Action<object>(o =>
                    {
                        Next();
                    }));
                }
                return nextPic;
            }
        }
        private BaseCommand? prePic;
        /// <summary>
        /// 上一张
        /// </summary>
        public BaseCommand PrePic
        {
            get
            {
                if (prePic == null)
                {
                    prePic = new BaseCommand(new Action<object>(o =>
                    {
                        Pre();
                    }));
                }
                return prePic;
            }
        }

        private BaseCommand? openDrawer;
        /// <summary>
        /// 打开列表抽屉
        /// </summary>
        public BaseCommand OpenDrawer
        {
            get
            {
                if (openDrawer == null)
                {
                    openDrawer = new BaseCommand(new Action<object>(o =>
                    {
                        IsOpenDrawer = !IsOpenDrawer;
                    }));
                }
                return openDrawer;
            }
        }

        private BaseCommand? changePic;
        /// <summary>
        /// 改变显示图片
        /// </summary>
        public BaseCommand ChangePic
        {
            get
            {
                if (changePic == null)
                {
                    changePic = new BaseCommand(new Action<object>(o =>
                    {
                        if (o != null)
                        {
                            if (o is ListBox listBox)
                            {
                                //var item = listBox.SelectedItem;
                                var item = (Pic)listBox.SelectedItem;
                                if(item != null)
                                {
                                    GoToPic(item);
                                }
                            }
                        }
                    }));
                }
                return changePic;
            }
        }

        private BaseCommand? importData;
        /// <summary>
        /// 导入数据
        /// </summary>
        public BaseCommand ImportData
        {
            get
            {
                if (importData == null)
                {
                    importData = new BaseCommand(new Action<object>(o =>
                    {
                        ImportDataList();
                    }));
                }
                return importData;
            }
        }

        private bool disposedValue;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    obj.Dispose();
                    pic?.Dispose();
                }

                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~PicsShowViewModel()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }
        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }


        #endregion

        #region 方法
        /// <summary>
        /// 下一页
        /// </summary>
        private void Next()
        {
            if (Pics != null && Pics.Any())
            {
                if (Pic != null && Pic.Index < Pics.Count && Pic.Index > 0)
                {
                    if (PreLoadStatus)
                    {
                        //预加载，不立刻释放，保留前两张与加载后两张
                        if (Pic.Index > 2 && Pic.Index < Pics.Count)
                        {
                            Pics[Pic.Index - 2]?.BitmapFrameE?.Dispose();
                        }
                        if (Pic.Index < Pics.Count - 2)
                        {
                            _ = Pics[Pic.Index + 1]?.BitmapFrameE?.Thumbnail;
                            _ = Pics[Pic.Index + 2]?.BitmapFrameE?.Thumbnail;
                        }
                    }
                    else
                    {
                        Pic.BitmapFrameE?.Dispose();
                    }
                    if (Pic.Index == Pics.Last().Index) Pic = Pics.FirstOrDefault();
                    else
                    {
                        Pic = Pics[Pic.Index];
                    }
                    //if (OriginalStatus)
                    //{
                    //    ShowNow = Pic?.BitmapFrameE?.BitmapImageSource;
                    //}
                    //else
                    //{
                    //    ShowNow = Pic?.BitmapFrameE?.Thumbnail;
                    //}
                }
                else
                {
                    Pic = Pics.FirstOrDefault();
                }
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        private void Pre()
        {
            if (Pics != null && Pics.Any())
            {
                if (Pic != null && Pic.Index > 0 && Pic.Index <= Pics.Count)
                {
                    if (PreLoadStatus)
                    {
                        //预加载，不立刻释放，加载前两张与保留后两张
                        if (Pic.Index > 2 && Pic.Index < Pics.Count)
                        {
                            _ = Pics[Pic.Index - 1]?.BitmapFrameE?.Thumbnail;
                            _ = Pics[Pic.Index - 2]?.BitmapFrameE?.Thumbnail;
                        }
                        if (Pic.Index < Pics.Count - 2)
                        {
                            Pics[Pic.Index + 2]?.BitmapFrameE?.Dispose();
                        }
                    }
                    else
                    {
                        Pic.BitmapFrameE?.Dispose();
                    }

                    if (Pic.Index == 1) Pic = Pics.LastOrDefault();
                    else
                    {
                        Pic = Pics[Pic.Index - 2];
                    }
                    //if (OriginalStatus)
                    //{
                    //    ShowNow = Pic?.BitmapFrameE?.BitmapImageSource;
                    //}
                    //else
                    //{
                    //    ShowNow = Pic?.BitmapFrameE?.Thumbnail;
                    //}
                }
                else
                {
                    Pic = Pics.LastOrDefault();
                }
            }
        }
        /// <summary>
        /// 跳转到指定页
        /// </summary>
        /// <param name="pic"></param>
        private void GoToPic(Pic pic)
        {
            if(pic!=null && pic.BitmapFrameE?.BaseUri != null)
            {
                Pic?.BitmapFrameE?.Dispose();
                Pic = pic;
            }
        }
        private void ImportDataList()
        {
            var textDialog = (TextDialogWindow)WindowManager.GetWindow("TextDialogWindow", null);
            if (textDialog != null)
            {
                textDialog.CallBackMethod = Method;
                textDialog.Show();
            }
        }
        private void Method(string text)
        {
            if (text == null) return;
            var urls = text.Split("\r\n") ?? text.Split("\n");
            if(urls!=null && urls.Any())
            {
                Pics?.Dispose();
                Pics?.Clear();
                Pics = new();
                for(int i = 0; i < urls.Length; i++)
                {
                    var url = urls[i].Replace("\"","").Trim(',').Trim();
                    Pics.Add(new Pic()
                    {
                        Title="导入图",
                        Subject= url,
                        Index = i+1,
                        BitmapFrameE = new(url)
                    });
                }
            }
        }
        #endregion
    }
}
